<!-- components/Account.vue -->
<template>
	<view class="container">
		<!-- 标题 -->
		<!-- <view class="header " >
			<image src="/static/index_slices/back_left.png" mode="" @click="toBack"></image>
			<text>我的邀请</text>
		
		</view> -->
		<view class="content">
			<view class="poster-container" id="posterHtml" ref="contentRef">
				<view class="invite">
					<!-- <view class="qrcode">我的邀请码<br/><text>{{posterCode}}</text></view> -->
					<image class="qrcode" :src="posterCode"></image>
				</view>
				<view class="operate flex-between">
					<view class="tit">操作流程</view>
					<view class="list " v-for="(item,index) in operateList" :key="index">
						<image :src="item.icon" mode="widthFix"></image>
						<view class="text">
							<text>{{item.text}}</text>
						</view>
					</view>
				</view>
			</view>
			<view class="btn" @click="copyUrl">
				复制邀请链接
			</view>
		</view>

	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		computed,
		onMounted,
		onUnmounted
	} from 'vue'
	import CustomNavbar from '@/components/CustomNavbar.vue';
	import html2canvas from 'html2canvas'
	// 保存海报
	const poster = ref('/otherPages/static/btn_bg.png')
	const posterUrl = ref()
	const contentRef = ref(null);
	const posterCode = ref('')
	const getParameterFromUrl = function(url, paramName) {
	  // 分离查询字符串和哈希部分
	  const [base, hash] = url.split('/#');
	  const [path, query] = hash.split('?');
	  
	  if (!query) return null;
	  
	  const params = query.split('&');
	  for (const param of params) {
	    const [key, value] = param.split('=');
	    if (key === paramName) {
	      return decodeURIComponent(value || '');
	    }
	  }
	  
	  return null;
	}
	const getQrcode = async () => {
		await uni.$api.user.qrcode().then(res => {
			posterUrl.value = res.data.invite_url;
			posterCode.value = res.data.qrcode
		})
	}
	getQrcode()
	//复制链接
	const copyUrl = () => {
		uni.setClipboardData({
			data: posterUrl.value,
			success: function() {
				uni.showToast({
					title: '复制成功,去邀请',
					duration: 2000,
					icon: 'none'
				});
			},
			fail: function(err) {
				uni.showToast({
					title: '复制失败',
					duration: 2000,
					icon: 'none'
				});
			}
		});
	}
	const savePoster = async () => {
		const element = contentRef.value?.$el;
		// 替换所有跨域图片为 Base64（可选）
		replaceCrossOriginImages(element);
		if (!element) {
			uni.showToast({
				title: '未找到截图区域',
				icon: 'none'
			});
			return;
		}

		try {
			// 调用 html2canvas
			const canvas = await html2canvas(element, {
				scale: 2,
				useCORS: true, // 是否尝试使用CORS从服务器加载图像
			})
			// 转换为 base64
			const imgData = canvas.toDataURL('image/png');

			// 下载图片（H5）
			const link = document.createElement('a');
			link.download = 'screenshot.png';
			link.href = imgData;
			link.click();

			uni.showToast({
				title: '保存成功'
			});


		} catch (err) {
			console.error('截图失败:', err);
			uni.showToast({
				title: '截图失败',
				icon: 'none'
			});
		}
	};
	// 替换跨域图片为 Base64
	const replaceCrossOriginImages = async (element) => {
		const images = element.querySelectorAll('img[src^="http"]');
		for (const img of images) {
			try {
				img.crossOrigin = 'anonymous';
				const blob = await fetch(img.src).then(res => res.blob());
				img.src = await new Promise(resolve => {
					const reader = new FileReader();
					reader.onload = () => resolve(reader.result);
					reader.readAsDataURL(blob);
				});
			} catch (e) {
				console.warn(`图片转换失败: ${img.src}`, e);
			}
		}
	}
	const saveImage = (tempFilePath) => {
		uni.saveImageToPhotosAlbum({
			filePath: tempFilePath,
			success: () => {
				uni.showToast({
					title: '保存成功'
				});
				isSaving.value = false;
			},
			fail: (err) => handleError(err)
		});
	};

	const handleError = (err) => {
		console.error(err);
		uni.showToast({
			title: '保存失败',
			icon: 'none'
		});
		isSaving.value = false;
	};
	// 操作
	const operateList = reactive(
		[{
				icon: '/otherPages/static/share.png',
				text: '生成海报保存分享给好友'
			},
			{
				icon: '/otherPages/static/friend.png',
				text: '好友扫码  接受邀请'
			},
			{
				icon: '/otherPages/static/authentication.png',
				text: '好友登录  完成认证'
			},
		])

	// 返回上一页
	const toBack = () => {
		uni.navigateBack({
			delta: 1 // 返回层数（默认1，表示返回上一页）
		});
	}
</script>

<style lang="scss" scoped>
	.container {
		position: fixed;
		top: 0;
		width: 100%;
		left: 0;
		overflow-y: scroll;
		height: 100vh;
		// background: url(/static/index_slices/底.png) no-repeat;
		background-size: 100% auto;
		// padding-top: 28rpx;
		background: radial-gradient(circle at center,
				#FD9674 0%,
				#FE8261 100%);

		// 标题
		.header {
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			padding: 30rpx;
			color: #fff;
			z-index: 999;
			text-align: left;
			padding-left: 89rpx;

			image {
				position: absolute;
				left: 30rpx;
				top: 38rpx;
				width: 20rpx;
				height: 38rpx;
			}
		}

		/* 导航栏高度 */
		.content {
			position: relative;
			padding-bottom: 120rpx;

			.btn {
				width: 526rpx;
				height: 101rpx;
				line-height: 101rpx;
				background: url('/otherPages/static/btn1_bg.png') no-repeat;
				background-size: 100%;
				position: absolute;
				left: 50%;
				transform: translateX(-50%);
				top: 60%;
				text-align: center;
				color: #4E301D;
				font-size: 34.7rpx;
			}

			.invite {
				position: relative;
				background-image: url('/otherPages/static/btn_bg.png');
				height: 654px;
				background-size: cover;
				text-align: center;
				overflow: hidden;

				image {
					width: 100%;
				}

				.qrcode {
					text-align: center;
					margin: 80% auto 0;
					width: 300rpx;
					height: 300rpx;
					text{
						display: block;
						margin-top: 30rpx;
						font-size: 50rpx;
						font-weight: bold;
					}
				}
			}

			.operate {
				width: 690rpx;
				height: 446rpx;
				margin-left: 30rpx;
				background: url('/otherPages/static/operate_bg.png') no-repeat;
				background-size: 100%;
				padding: 141rpx 47rpx 100rpx 47rpx;
				box-sizing: border-box;
				margin-top: 25rpx;
				position: relative;
				.tit{
					position: absolute;
					left: 50%;
					top: 10rpx;
					transform: translatex(-50%);
					color: white;
					font-size: 38rpx;
				}
				.list {
					text-align: center;
					font-size: 28rpx;
					color: #333333;
					max-width: 169rpx;

					image {
						width: 106rpx;
						height: 106rpx;
						margin-bottom: 32rpx;
					}
				}
			}
		}
	}
</style>